package com.chenfan.finance.service.impl;

import cn.afterturn.easypoi.csv.entity.CsvImportParams;
import cn.afterturn.easypoi.csv.imports.CsvImportService;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.alibaba.fastjson.JSONObject;
import com.chenfan.finance.dao.*;
import com.chenfan.finance.model.TocAlipayOrigin;
import com.chenfan.finance.model.dto.AlipayOriginExcelDTO;
import com.chenfan.finance.utils.BeanUtilCopy;
import com.chenfan.finance.utils.TrashBagList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Service
public class TocImportDataServiceImpl {
    @Autowired
    private TocAlipayOriginMapper tocAlipayOriginMapper;
    @Autowired
    private TocAlipayMappingIncomeMapper incomeMapper;
    @Autowired
    private TocAlipayMappingExpendMapper expendMapper;
    @Autowired
    private TocU8HeaderMapper tocU8HederMapper;
    @Autowired
    private TocU8DetailMapper tocU8DetailMapper;


    public List<Map<String, String>> impotData(MultipartFile[] files) throws Exception {
        List<Map<String, String>> msgs = new LinkedList<>();

        for (MultipartFile file : files) {
            if (file == null) {
                continue;
            }
            // List<AlipayOriginExcelDTO> fileModels = importExcel(file, 0, 1, AlipayOriginExcelDTO.class);
            List<AlipayOriginExcelDTO> fileModels = importCvs(file, AlipayOriginExcelDTO.class);

            List<TocAlipayOrigin> alipays = new ArrayList<>(fileModels.size());
            for (AlipayOriginExcelDTO fileModel : fileModels) {
                TocAlipayOrigin alipayOrigin = convertToModel(fileModel);
                alipays.add(alipayOrigin);
            }
            String msg = insertDb(alipays);
            Map<String, String> d = new HashMap<>(4);
            d.put(file.getOriginalFilename(), msg);
            msgs.add(d);
        }
        return msgs;
    }

    /**
     * CsvImportParams 的参数描述如下
     * 属性 | 类型 | 默认值 | 功能
     * —————–|———————|——–|———————
     * encoding | String | UTF8 | 文件编码
     * spiltMark | String | , | 分隔符
     * textMark | String | “ | 字符串识别,可以去掉,需要前后一致
     * titleRows | int | 0 | 表格头,忽略
     * headRows | int | 1 | 标题
     * startRows | int | 0 | 标题起忽略行数
     * verifyGroup | Class[] | null | 校验,参考java validation
     * needVerify | boolean | false | 是否需要校验,默认false
     * verifyHandler | IExcelVerifyHandler | null | 自定义校验接口
     * lastOfInvalidRow | int | 0 | 最后跳过行
     * keyIndex | int | null | 重要字段,判断是否需要读取
     * <p>
     * }
     */
    private List<AlipayOriginExcelDTO> importCvs(MultipartFile file, Class<AlipayOriginExcelDTO> clazz) throws IOException {
        CsvImportParams params = new CsvImportParams(CsvImportParams.GBK);
        params.setTitleRows(4);
        params.setLastOfInvalidRow(4);
//        CsvImportUtil.importCsv(
//                      file.getInputStream(),
//                clazz, params, new IReadHandler() {
//                    @Override
//                    public void handler(Object o) {
//
//                    }
//
//                    @Override
//                    public void doAfterAll() {
//
//                    }
//                });
        return new CsvImportService().readExcel(file.getInputStream(), clazz, params, null);
    }


    private List<AlipayOriginExcelDTO> importExcel(MultipartFile file, int i, int i1, Class<AlipayOriginExcelDTO> alipayOriginExcelDTOClass) throws IOException {
        ExcelUtil.readBySax(file.getInputStream(), 1, new RowHandler() {
            @Override
            public void handle(int sheetIndex, int rowIndex, List<Object> rowList) {
                System.out.println(sheetIndex + "_" + rowIndex + JSONObject.toJSONString(rowList));
            }
        });
        return new LinkedList<>();
    }


    private String insertDb(List<TocAlipayOrigin> alipays) {
        int insert = 5000;
        if (alipays.size() < insert) {
            insert = alipays.size();
        }
        int loop = alipays.size() / insert;
        long startTime = System.currentTimeMillis();
        int result = 0;
        for (int i = 0; i < loop; i++) {
            int start = i * insert;
            int end = (i + 1) * insert;
            if (loop - 1 == i) {
                end = alipays.size();
            }
            int sum = tocAlipayOriginMapper.insertList(alipays.subList(start, end));
            result = sum + result;
        }
        long endTime = System.currentTimeMillis();
        return "插入总数: " + result + " ，耗时： " + (endTime - startTime) / 1000 + " s.";
    }

    private TocAlipayOrigin convertToModel(AlipayOriginExcelDTO fileModel) {

        TocAlipayOrigin alipayOrigin = BeanUtilCopy.copyPropertiesIgnoreType(fileModel, TocAlipayOrigin.class);
        return alipayOrigin;
    }


    public static void main(String[] args) {
        List<TocAlipayOrigin> origin = new ArrayList<>();
        TocAlipayOrigin alipayOrigin = new TocAlipayOrigin();
        alipayOrigin.setFinanceNo("002");
        alipayOrigin.setAccountLeftAmount(BigDecimal.ONE);
        TocAlipayOrigin alipayOrigin1 = new TocAlipayOrigin();
        alipayOrigin1.setFinanceNo("001");
        alipayOrigin1.setAccountLeftAmount(BigDecimal.ONE);
        origin.add(alipayOrigin1);
        origin.add(alipayOrigin);
        List<TocAlipayOrigin> origins = new TrashBagList<TocAlipayOrigin>().trashBag(origin, TocAlipayOrigin::getFinanceNo, TocAlipayOrigin::getAccountLeftAmount, BigDecimal.ONE);
        System.out.println(origins);
    }

}
